package mvc;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.action.Action;
import mvc.form.FillForm;
import mvc.form.Form;
import mvc.xml.XmlBean;

/**
 * 控制器核心类
 * 
 * @author jiangchao
 *
 */
public class ActionServlet extends HttpServlet {

	/**
	 * 序列号
	 */
	private static final long serialVersionUID = -8546128923857009898L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		获取实际访问路径
		String path = extractPath(req.getServletPath());
		try {
//			web项目需要根据url的不同执行不同的业务过程，因此设计请求路径和xml解析对象进行映射
//			通过特定的监听器获得请求路径和xml解析对象的映射关系
			Map<String, XmlBean> map = (Map<String, XmlBean>) this.getServletContext().getAttribute("structs");
			XmlBean xmlBean = map.get(path);
//			通过解析对象的formClass值实例化并填充对应的表单对象
			Form form = FillForm.fill(req, xmlBean.getFormClass());
//			通过解析对象的actionType值实例化业务操作单元
			String actionType = xmlBean.getActionType();
			Class actionClass = Class.forName(actionType);
			Action action = (Action) actionClass.newInstance();
//			利用模板方法设计模式，将填充好的表单对象交给子类去转化为具体的表单对象
			String url = action.execute(req, form, xmlBean.getForward());
//			处理页面的跳转
			RequestDispatcher dis = req.getRequestDispatcher(url);
			dis.forward(req, resp);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("类对象未找到");
		} catch (InstantiationException e) {
			e.printStackTrace();
			System.out.println("类实例化对象失败");
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("无法访问对象");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}

	private String extractPath(String path) {
//		提取访问路径
		return path.split("\\.")[0];
	}
}
